const mongoose=require('mongoose');
const moment=require('moment');
const md=require('markdown-it')({breaks:true});
const config=require('../config/config');
const isNaturalNumber=require('../lib/isNaturalNumber');
moment.locale('zh-cn');

const PostSchema=new mongoose.Schema({
    title:{
        type:String,
        required:true
    },
    tags:{
        type:Array,
        enum:config.post.tags,
        required:true
    },
    content:{
        type:String,
        required:true
    },
    intro:{
        type:String,
        required:true
    },
    author:{
        type:mongoose.Schema.ObjectId,
        ref:'User',
        required:true
    },
    comments:[{
        type:mongoose.Schema.ObjectId,
        ref:'Comment'
    }],
    pv:{
        type:Number,
        default:0,
        required:true
    },
    reprintUsers:[
        {
            type:mongoose.Schema.ObjectId,
            ref:'User'
        }
    ],
    reprintFrom:{
        type:mongoose.Schema.ObjectId,
        ref:'Post'
    },
    time:{
        type:Date,
        required:true
    },
    archive:{
        type:String,
        required:true
    }
});

PostSchema.virtual('timeStr').get(function(){
    return moment(this.time).format('YYYY-MM-DD HH:mm:ss');
});

PostSchema.virtual('ago').get(function(){
    return moment(this.time).fromNow();
});

PostSchema.virtual('contentHTML').get(function(){
    return md.render(this.content);
});

PostSchema.statics.page=function(query,fields,{page=1,limit=config.post.limit}={page:1,limit:config.post.limit}){
    page=isNaturalNumber(page)?Number(page):1;
    limit=isNaturalNumber(limit)?Number(limit):config.post.pageLimit;
    limit=limit>config.post.pageLimit?config.post.pageLimit:limit;
    return Promise.all([
        Promise.resolve({page,limit}),
        this.count(query).then(count=>Math.ceil(count/limit)),
        this.find(query,fields,{skip:(page-1)*limit,limit:limit,sort:{time:-1,title:1}})
    ]).then(ret=>{
        return {
            total:ret[1],
            page:ret[0].page,
            limit:ret[0].limit,
            posts:ret[2]
        }
    });
};

module.exports=mongoose.model('Post',PostSchema);